﻿using COSXML;
using COSXML.Auth;
using COSXML.Model.Object;
using Md.Api.DDD;
using Md.Api.Model.Util.Oss.Request;
using Md.Api.Model.Util.Oss.Response;

namespace Md.Util.Service.Oss;
/// <summary>
/// 腾讯云Cos文件下载服务
/// 参考文档：
/// https://cloud.tencent.com/document/product/436/6474
/// https://cloud.tencent.com/document/product/436/47230
/// </summary>
public class TencentCosDownloadService : ApiBase<RequestTencentCosDownloadModel>
{
    protected override void ExecuteMethod()
    {
        if (string.IsNullOrWhiteSpace(Parameter.YunFileName))
        {
            throw new AggregateException("云文件名称不能为空");
        }

        //每次请求签名有效时长，单位为秒
        long durationSecond = 600;

        // 地域
        var region = JsonConfig.JsonRead("MdTencent:OSSTx:Region");

        var secretId = JsonConfig.JsonRead("MdTencent:SecretId");

        var secretKey = JsonConfig.JsonRead("MdTencent:SecretKey");

        //存储桶，格式：BucketName-APPID
        var bucketName = JsonConfig.JsonRead("MdTencent:OSSTx:BucketName");

        //指定本地保存的文件名
        var ext = Parameter.YunFileName.Split(".")[1];
        var localFileName = $"{DateTime.Now.ToString("yyyyMMddHHmmssffff")}.{ext}";

        var qCloudCredentialProvider = new DefaultQCloudCredentialProvider(secretId, secretKey, durationSecond);

        var config = new CosXmlConfig.Builder()
          .SetRegion(region) // 设置默认的地域, COS 地域的简称请参照 https://cloud.tencent.com/document/product/436/6224
          .Build();

        var cosXml = new CosXmlServer(config, qCloudCredentialProvider);

        var request = new GetObjectRequest(bucketName, Parameter.YunFileName, FileBasePath, localFileName);
        //设置进度回调
        request.SetCosProgressCallback(delegate (long completed, long total)
        {
            Console.WriteLine(string.Format("progress = {0:##.##}%", completed * 100.0 / total));
        });

        //执行请求
        var result = cosXml.GetObject(request);

        if (result.httpCode == 200 && result.httpMessage == "OK")
        {
            var responseModel = new ResponseTencentOSSDownloadModel();
            responseModel.localFilePath= $"{FileBasePath}/{localFileName}";
            responseModel.yunFilePath = Parameter.YunFileName;

            Result.Data = responseModel;
            Result.Msg = "success";
        }
        else
        {
            throw new AggregateException(result.httpMessage);
        }
    }
}

